#!/usr/bin/env node

/**
 * 数据库连接测试脚本
 * 测试所有数据库的连接状态和配置
 */

import pg from 'pg';
import redis from 'redis';
import { MongoClient } from 'mongodb';
import fs from 'fs';

// 加载环境变量
const envFile = fs.readFileSync('.env', 'utf8');
const envVars = {};

envFile.split('\n').forEach(line => {
    if (line.trim() && !line.startsWith('#')) {
        const [key, value] = line.split('=');
        if (key && value) {
            envVars[key.trim()] = value.trim();
        }
    }
});

// 数据库配置
const dbConfig = {
    postgresql: {
        host: envVars.DB_HOST || 'localhost',
        port: parseInt(envVars.DB_PORT) || 5432,
        database: envVars.DB_NAME || 'bike_wholesale',
        user: envVars.DB_USER || 'postgres',
        password: envVars.DB_PASSWORD || 'password'
    },
    redis: {
        host: envVars.REDIS_HOST || 'localhost',
        port: parseInt(envVars.REDIS_PORT) || 6379,
        password: envVars.REDIS_PASSWORD || '',
        db: parseInt(envVars.REDIS_DB) || 0
    },
    mongodb: {
        uri: envVars.MONGODB_URI || 'mongodb://localhost:27017/bike_community',
        database: envVars.MONGODB_DB || 'bike_community'
    }
};

console.log('🚀 数据库连接测试开始...\n');

// 测试PostgreSQL连接
async function testPostgreSQL() {
    console.log('🔍 测试PostgreSQL连接...');
    
    const client = new pg.Client({
        host: dbConfig.postgresql.host,
        port: dbConfig.postgresql.port,
        database: dbConfig.postgresql.database,
        user: dbConfig.postgresql.user,
        password: dbConfig.postgresql.password,
        connectionTimeoutMillis: 5000
    });
    
    try {
        await client.connect();
        const result = await client.query('SELECT version(), current_timestamp, current_database()');
        console.log('✅ PostgreSQL连接成功!');
        console.log('   数据库版本:', result.rows[0].version.split(',')[0]);
        console.log('   当前数据库:', result.rows[0].current_database);
        console.log('   连接时间:', result.rows[0].current_timestamp);
        
        // 测试数据库操作
        const testTable = await client.query(`
            SELECT EXISTS (
                SELECT FROM information_schema.tables 
                WHERE table_schema = 'public' 
                AND table_name = 'users'
            ) as table_exists
        `);
        
        if (testTable.rows[0].table_exists) {
            console.log('   ✅ users表存在');
        } else {
            console.log('   ⚠️ users表不存在');
        }
        
        await client.end();
        return { success: true, message: 'PostgreSQL连接正常' };
    } catch (error) {
        console.log('❌ PostgreSQL连接失败:', error.message);
        return { success: false, message: error.message };
    }
}

// 测试Redis连接
async function testRedis() {
    console.log('\n🔍 测试Redis连接...');
    
    const client = redis.createClient({
        socket: {
            host: dbConfig.redis.host,
            port: dbConfig.redis.port
        },
        password: dbConfig.redis.password || undefined,
        database: dbConfig.redis.db
    });
    
    try {
        await client.connect();
        const pong = await client.ping();
        
        if (pong === 'PONG') {
            console.log('✅ Redis连接成功!');
            
            // 测试基本操作
            await client.set('test_connection', 'success', {
                EX: 10 // 10秒后过期
            });
            
            const value = await client.get('test_connection');
            console.log('   测试键值:', value);
            
            await client.del('test_connection');
            
            // 获取Redis信息
            const info = await client.info('server');
            const versionLine = info.split('\n').find(line => line.startsWith('redis_version'));
            if (versionLine) {
                console.log('   Redis版本:', versionLine.split(':')[1]);
            }
            
            await client.quit();
            return { success: true, message: 'Redis连接正常' };
        } else {
            throw new Error('PING响应异常');
        }
    } catch (error) {
        console.log('❌ Redis连接失败:', error.message);
        return { success: false, message: error.message };
    }
}

// 测试MongoDB连接
async function testMongoDB() {
    console.log('\n🔍 测试MongoDB连接...');
    
    let client;
    try {
        client = new MongoClient(dbConfig.mongodb.uri, {
            serverSelectionTimeoutMS: 5000,
            connectTimeoutMS: 5000
        });
        
        await client.connect();
        
        // 测试连接
        await client.db().admin().ping();
        console.log('✅ MongoDB连接成功!');
        
        // 获取服务器信息
        const serverInfo = await client.db().admin().serverStatus();
        console.log('   MongoDB版本:', serverInfo.version);
        console.log('   当前数据库:', dbConfig.mongodb.database);
        
        // 测试数据库操作
        const db = client.db(dbConfig.mongodb.database);
        const collections = await db.listCollections().toArray();
        console.log('   集合数量:', collections.length);
        
        await client.close();
        return { success: true, message: 'MongoDB连接正常' };
    } catch (error) {
        console.log('❌ MongoDB连接失败:', error.message);
        if (client) {
            await client.close();
        }
        return { success: false, message: error.message };
    }
}

// 主测试函数
async function runAllTests() {
    const results = {
        postgresql: await testPostgreSQL(),
        redis: await testRedis(),
        mongodb: await testMongoDB()
    };
    
    console.log('\n📊 测试结果汇总:');
    console.log('==================');
    
    Object.entries(results).forEach(([db, result]) => {
        const status = result.success ? '✅' : '❌';
        console.log(`${status} ${db.toUpperCase()}: ${result.success ? '连接正常' : '连接失败'}`);
    });
    
    console.log('==================');
    
    // 检查是否所有数据库都连接成功
    const allSuccess = Object.values(results).every(r => r.success);
    const anySuccess = Object.values(results).some(r => r.success);
    
    if (allSuccess) {
        console.log('🎉 所有数据库连接测试通过！服务器可以正常连接数据库。');
    } else if (anySuccess) {
        console.log('⚠️ 部分数据库连接成功，服务器可以在降级模式下运行。');
    } else {
        console.log('❌ 所有数据库连接失败，请检查数据库配置和服务状态。');
    }
    
    return results;
}

// 执行测试
runAllTests().catch(error => {
    console.error('测试过程中发生错误:', error);
    process.exit(1);
});